package org.dreamwork.cai.monitor.ws;

import com.google.gson.Gson;
import org.dreamwork.cai.srf.ServiceRouteTable;
import org.dreamwork.injection.IObjectContext;
import org.dreamwork.websocket.AbstractWebSocketExecutor;
import org.dreamwork.websocket.IWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;

@IWebSocket (value = "/ws/monitor", header = true, parameter = true, httpSession = true, servletContext = true)
public class MonitorWebSocket extends AbstractWebSocketExecutor<Command> {
    private final Logger logger = LoggerFactory.getLogger (MonitorWebSocket.class);

    private final Gson g = new Gson ();

    private String sessionId;

    @Override
    protected String cast (Command o) {
        return g.toJson (o);
    }

    @Override
    protected void onConnected (Session session) {
        if (application == null) {
            logger.warn ("servlet application context is not ready");

            return;
        }

        if (logger.isTraceEnabled ()) {
            logger.trace ("A new client connected. id = {}", sessionId = session.getId ());
        }

        IObjectContext ctx = (IObjectContext) application.getAttribute (IObjectContext.class.getCanonicalName ());
        if (ctx == null) {
            logger.warn ("object injection context not found.");

            return;
        }

        ServiceRouteTable table = ctx.getBean (ServiceRouteTable.class);
        if (table == null) {
            logger.warn ("no service route table!");
            return;
        }

        send (new Command ("create", table));
    }

    @Override
    protected void onDisconnected () {
        if (logger.isTraceEnabled ()) {
            logger.trace ("Client[{}] disconnected", sessionId);
        }
        sessionId = null;
    }

    /*
    @Override
    public void onMessage (String message) {
        logger.info ("received message: {}", message);
        logger.info ("parameter = {}", parameters);
        logger.info ("session = {}", httpSession);
        logger.info ("header = {}", headers);
        logger.info ("servlet context = {}", application);

        send (message);
    }
 */
}
